package oneday.one;

import org.junit.Test;

import java.util.Iterator;

/**
 * Created by ZPF on 2019/10/29.
 * 增强for示例代码
 */
public class Demo3 {
    @Test
    public void func(){
        Word word = new Word("abcd edf hijk lmn");
        for(String s: word){
            System.out.println(s);
        }
    }
}
class Word implements  Iterable<String>{
    private String text;
    public Word(String s){
        this.text=s;
    }

    @Override
    /*
        * 希望每次遍历一个单词
     */
    public Iterator<String> iterator() {
        return new Iterator<String>() {
            private String[] wordArray = text.split("\\s+");
            private int index =0;//表示从0下标开始遍历
            @Override
            public boolean hasNext() {
                return index < wordArray.length;
            }

            @Override
            public String next() {
                return wordArray[index++];
            }
        };
    }
}
